#ifndef SUBJECT_LIB_H
#define SUBJECT_LIB_H

#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>

#include "Subject.h"


using namespace std;

void Add_subject(string s, Subject l[], int &numberSubject){
    string temp, a_id, a_sname, a_stype, a_presub;
    short a_credit, a_percent_midterm;

    int mark = s.find(":");
    a_id = s.substr(0,mark);

    temp = s.substr(mark+1);
    mark = temp.find(":");
    a_sname = temp.substr(0,mark);

    temp = temp.substr(mark+1);
    mark = temp.find(":");
    a_stype = temp.substr(0,mark);

    temp = temp.substr(mark+1);
    mark = temp.find(":");
    a_credit = atoi(temp.substr(0,mark).c_str());

    temp = temp.substr(mark+1);
    mark = temp.find(":");
    a_presub = temp.substr(0,mark);

    temp = temp.substr(mark+1);
    mark = temp.find(":");
    a_percent_midterm = atoi(temp.substr(0,mark).c_str());

    Subject Sub(a_id, a_sname, a_stype, a_credit, a_presub, a_percent_midterm);
    l[numberSubject] = Sub;
    numberSubject = numberSubject + 1;
}

void Read_subject(string _file, Subject l[], int &numberSubject){
    ifstream fin;
    fin.open(_file.c_str());
    if(!fin.is_open()){
        cout<<"Cannot open file.\n";
        exit(1);
    }else{
        string s = "";
        while (getline(fin, s)){
            Add_subject(s,l,numberSubject);
        }
        fin.close();
    }
}

Subject Get_subject_by_id(string key, Subject l[], int numberSubject){
    int i = 0;

    Subject result("", "", "", 0, "", 0);

    for (i = 0; i < numberSubject; i++){
        if (l[i].Get_id() == key){
            return l[i];
        }
    }

    return result;
}

Subject Get_presub_by_id(Subject subject, Subject l[], int numberSubject){
    string _presub = subject.Get_presub();

    Subject result("", "", "", 0, "", 0);

    if (_presub != "NONE"){
        result = Get_subject_by_id(_presub, l, numberSubject);
    }

    return result;
}

#endif // SUBJECT_LIB_H
